import { createRouter, createWebHashHistory } from "vue-router";
import CcLogin from "./views/CcLogin.vue";
import CcMain from "./views/CcMain.vue";
import { useAdminStore } from "./store/admin";

//路由词典
const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: CcLogin,
        meta: {title: '管理员登录'}
    },
    {
        path: '/main',
        component: CcMain,    
        // component: ()=>import('./views/CcMain.vue'),        //懒加载优化
        meta: {title: '管理主菜单'},
        children: [
            {
                path: 'xtdlb',      //  /main/xtdlb
                component: ()=>import('./views/CcXieTiaoDanLieBiao.vue'),
                meta: {title: '协调单列表'}
            },
            {
                path: 'xjxtd',
                component: ()=>import('./views/CcXinJianXieTiaoDan.vue'),
                meta: {title: '新建协调单'}
            }
        ]
    }
]

//路由器对象
const router = createRouter({
    routes,     //路由词典
    history: createWebHashHistory()  //基于#开头的路由地址历史记录
})

//配置路由守卫
router.beforeEach((to, from)=>{         //每一次跳转之前
    // console.log('即将进行路由跳转，从：', from)
    // console.log('即将进行路由跳转，到：', to)   
    //业务：如果客户端直接希望访问非/login页，必须检查是否登录了；没有登录的话强制跳转到/login
    // let token = sessionStorage['loginToken']
    let adminStore = useAdminStore()
    let token = adminStore.adminToken
    if(!token && to.path != '/login'){
        console.log('用户希望跳转到：',to.path,' 但是尚未登录，即将跳转到登录页')
        return '/login'         //强制页面跳转
    } 

    //return to.path   //默认返回值
})

router.afterEach((to, from)=>{          //每一次跳转之后
    // console.log('路由跳转之后，从：', from)    
    // console.log('路由跳转之后，到：', to)    
    //根据当前路由提供的meta数据来修改页面标题
    let title = to.meta.title as string
    if(title){
        window.document.title = title 
    }
})


export default router